#include "database.h"

#include "databaseprivate.h"
#include "component_log.h"
#include "systemconfiguration.h"
#include "sql_data.h"
DataBase::DataBase(QObject* parent)
	: ComponentBase(parent)
{
	m_name = u8"数据库组件";
	m_type = Component::component_sql;
}

DataBase::~DataBase()
{}


// 组件初始化处理函数
int DataBase::ComponentInit()
{
	m_db = new DataBasePrivate();
	QString path = syscfg->GetSqlPath();
	if (!m_db->InitDB(path)) {
		SetErrmsg("数据库初始化失败");
	}
	m_data.clear();
	return 0;
}

/*自检接口*/
bool DataBase::ComponentCheckSelfState()
{
	return true;
}

/*复位接口*/
bool DataBase::ComponentSelfReset()
{
	return true;
}

void DataBase::ResponseSystemState(int state)
{
	SystemStateType st = (SystemStateType)state;
	switch (st) {
	case SystemStateType::system_state_idle:
		break;
	case SystemStateType::system_state_work:

		break;
	case SystemStateType::system_state_stop:

		break;
	default:
		log_error("system state error [{}]", state)
			break;
	}
}

bool DataBase::ReadData(const QString& table, const int id, QStringList& data)
{
	data = m_db->ReadDataByID(table, id, "data");
	return data.size() > 0 ? true : false;
}

// 命令执行接口
bool DataBase::ExcuteCmd(int cmd, const QByteArray& input, QByteArray& output)
{
	SqlCmdType type = (SqlCmdType)cmd;

	switch (type) {
	case SqlCmdType::sql_read_data:
	{
		SqlReadIn in = {};
		in.fromJson(input);
		QStringList data;
		if (ReadData(in.table(), in.id(), data)) {
			SqlReadOut out = {};
			out.data().append(data);
			output = out.toByteArray();
			return true;
		}
		output = "数据库为空";
		return false;
	}
	break;
	case SqlCmdType::sql_add_data:
	{
		SqlWriteIn in = {};
		in.fromJson(input);
		QStringList key = { "data" };
		QStringList vel = { in.data() };
		if (m_db->IfTableHasId(in.table(), in.id())) {
			return m_db->UpdataDataByID(in.table(), in.id(), key, vel);
		} else {
			return m_db->InsertDataByID(in.table(), in.id(), key, vel);
		}
	}
	break;
	case SqlCmdType::sql_delete_data:
	{
		SqlReadIn in = {};
		in.fromJson(input);
		if (in.id() > 0) {
			return m_db->DeleteDataByID(in.table(), in.id());
		} else {
			return m_db->DeleteAllData(in.table());
		}
	}

	break;
	case SqlCmdType::sql_update_data:
	{
		SqlWriteIn in = {};
		in.fromJson(input);
		QStringList key = { "data" };
		QStringList vel = { in.data() };
		if (m_db->IfTableHasId(in.table(), in.id())) {
			return m_db->UpdataDataByID(in.table(), in.id(), key, vel);
		} else {
			return m_db->InsertDataByID(in.table(), in.id(), key, vel);
		}
	}
	break;
	case SqlCmdType::sql_create_table:
	{
		QString table = input;
		if (m_db->IfTableExist(table)) {
			return true;
		} else {
			QStringList key = { "id", "data" };
			QStringList type = { "INT PRIMARY KEY", "TEXT" };
			return m_db->CreatTable(table, key, type);
		}
	}

	break;
	case SqlCmdType::sql_cmd_max:
		break;
	default:
		break;
	}

	return false;
}
